import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description: TCP回显客户端
 */
public class TcpEchoClient {
    //需要先创建一个实例，来与服务器进行连接和网络通信
    private Socket socket = null;
    private String serverIP = null;
    private int serverPort = 0;

    //此时指定的IP和端口号是要连接的服务器的
    public TcpEchoClient(String serverIP, int serverPort) throws IOException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        socket = new Socket(serverIP, serverPort);
    }

    //与服务器进行网络通信
    public void start() {
        System.out.println("与服务器连接成功");
        Scanner scanner = new Scanner(System.in);
        //我们需要将字符串写入socket的输入流，就需要先创建出来输入输出流实例
        try(InputStream inputStream = socket.getInputStream()) {
            try(OutputStream outputStream = socket.getOutputStream()) {
                while(true) {
                    //建立连接之后我们需要进行四步操作
                    //1. 从控制台读取用户输入的字符串
                    System.out.print("-> ");
                    String request = scanner.next();
                    //2. 用读取的字符串构造一个请求，然后发给服务器
                    PrintWriter printWriter = new PrintWriter(outputStream);
                    printWriter.println(request);
                    //传一个请求就刷新一次，保证服务器能立即看到请求并响应
                    printWriter.flush();
                    //3. 接收服务器传过来的响应并解析
                    Scanner respScanner = new Scanner(inputStream);
                    String response = respScanner.next();
                    //4. 把服务器的响应打印到控制台
                    System.out.printf("req: %s, resp: %s\n", request, response);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        TcpEchoClient tcpEchoClient = new TcpEchoClient("127.0.0.1", 9090);
        tcpEchoClient.start();
    }
}
